package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.blue.ui.DynamicWaveFormView;
import androidx.appcompat.app.AlertDialog;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;


public class MagCorActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "MagCorActivity";
    private Button startButton;
    private String deviceId;
    private  BluetoothService bluetoothService;
    private boolean isBound = false;
    private Handler handler = new Handler(Looper.getMainLooper());
    private Boolean saveCorrectCiliFlag=false;
    private Integer saveCorrectCiliNum=0;
    private static final Integer correctCiliNumSum=2000;
    private String bleRawData;
    private String saveCiliArray;
    private String saveRawArray;
    private String rawDataAbsFilepath;
    private String rawoutAbsFilepath;
    private String magBiasAbsFilepath;
    private DynamicWaveFormView waveformViewX;
    private DynamicWaveFormView waveformViewY;
    private DynamicWaveFormView waveformViewZ;
    private Thread workerThreadx;
    private Thread workerThready;
    private Thread workerThreadz;
    private Boolean runningx=false;
    private Boolean runningy=false;
    private Boolean runningz=false;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
    private DataProcessorManager processorManager;
    private final ConcurrentLinkedQueue<Float> magxDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magyDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magzDataQueue = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();


    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            dataQueue  = bluetoothService.getDataQueue();
//            if(dataQueue.isEmpty()){
//                new AlertDialog.Builder(MagCorActivity.this)
//                        .setTitle("提示")
//                        .setMessage("未收到数据，请重试")
//                        .setPositiveButton("确定", (dialog, which) -> {
//                            finish();
//                        })
//                        .show();
//            }else {
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManager.startProcessing();
//            }
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
            Log.d("ServiceTest", "Service disconnected");
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mag_cor);
        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(MagCorActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("磁力计校准");

        waveformViewX = findViewById(R.id.waveformView1);
        waveformViewY = findViewById(R.id.waveformView2);
        waveformViewZ = findViewById(R.id.waveformView3);
        waveformViewX.setYtitle("X轴磁力计(高斯)");
        waveformViewX.setYRange(-2,2);
        waveformViewY.setYtitle("Y轴磁力计(高斯)");
        waveformViewY.setYRange(-2,2);
        waveformViewZ.setYtitle("Z轴磁力计(高斯)");
        waveformViewZ.setYRange(-2,2);

        spinner = findViewById(R.id.modeSpinner);
        String[] options = {"传感器1", "传感器2", "传感器3", "传感器4", "传感器5", "传感器6"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
// 监听选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX.clearDataPoints();
                    waveformViewY.clearDataPoints();
                    waveformViewZ.clearDataPoints();
                }
                selectedSensorNum=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        startButton = findViewById(R.id.magCorrectBtn);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                saveCorrectCiliFlag=true;
                Toast.makeText(MagCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                String mac=deviceId.replace(":", "");
                System.out.println("magcor----mac:"+mac);
                processorManager.setDeviceMac(mac);
                processorManager.setDataUpdateListener(MagCorActivity.this);
//                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.MagBias);
                System.out.println("magcor----processorManager:"+processorManager);

            }
        });

    }
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, BluetoothService.class);
        intent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        System.out.println("onDataProcessed:"+data.toString());
        String processedValue = data.getValue();
      //  dataTextView.setText("收到数据: " + processedValue);
        String flag = data.getFlag();
        System.out.println("magcor-Flag:"+flag);
        if(flag.equals("rawout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
          //  System.out.println("dataArr: " + dataArr);
            switch(selectedSensorNum){
                case 0:
                    String da1 = dataArr[6].length()>10?dataArr[6].substring(0,8):dataArr[6];
                    String da2 = dataArr[7].length()>10?dataArr[7].substring(0,8):dataArr[7];
                    String da3 = dataArr[8].length()>10?dataArr[8].substring(0,8):dataArr[8];
                    if(!da1.equals("0")) {
                        System.out.println("magcor-Hex: " + processedValue);
                       // magxDataQueue.add(Float.parseFloat(da1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(da1) * 10000);
                    }
                    if(!da2.equals("0")) {
                       // magyDataQueue.add(Float.parseFloat(da2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(da2) * 10000);
                    }
                    if(!da3.equals("-0")) {
                       // magzDataQueue.add(Float.parseFloat(da3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(da3) * 10000);
                    }
                    break;
                case 1:
                    String dd1 = dataArr[15].length()>10?dataArr[15].substring(0,8):dataArr[15];
                    String dd2 = dataArr[16].length()>10?dataArr[16].substring(0,8):dataArr[16];
                    String dd3 = dataArr[17].length()>10?dataArr[17].substring(0,8):dataArr[17];

                    if(!dd1.equals("0")) {
                       // magxDataQueue.add(Float.parseFloat(dd1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(dd1) * 10000);

                    }
                    if(!dd2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(dd2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(dd2) * 10000);

                    }
                    if(!dd3.equals("-0")) {
//                        magzDataQueue.add(Float.parseFloat(dd3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(dd3) * 10000);

                    }
                    break;
                case 2:
                    String de1 = dataArr[24].length()>10?dataArr[24].substring(0,8):dataArr[24];
                    String de2 = dataArr[25].length()>10?dataArr[25].substring(0,8):dataArr[25];
                    String de3 = dataArr[26].length()>10?dataArr[26].substring(0,8):dataArr[26];
                    if(!de1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(de1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(de1) * 10000);

                    }
                    if(!de2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(de2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(de2) * 10000);

                    }

                    if(!de3.equals("-0")) {
//                        magzDataQueue.add(Float.parseFloat(de3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(de3) * 10000);

                    }
                    break;
                case 3:
                    String df1 = dataArr[33].length()>10?dataArr[33].substring(0,8):dataArr[33];
                    String df2 = dataArr[34].length()>10?dataArr[34].substring(0,8):dataArr[34];
                    String df3 = dataArr[35].length()>10?dataArr[35].substring(0,8):dataArr[35];
                    if(!df1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(df1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(df1) * 10000);

                    }
                    if(!df2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(df2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(df2) * 10000);

                    }
                    if(!df3.equals("-0")) {
//                        magzDataQueue.add(Float.parseFloat(df3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(df3) * 10000);

                    }
                    break;
                case 4:
                    String dc1 = dataArr[42].length()>10?dataArr[42].substring(0,8):dataArr[42];
                    String dc2 = dataArr[43].length()>10?dataArr[43].substring(0,8):dataArr[43];
                    String dc3 = dataArr[44].length()>10?dataArr[44].substring(0,8):dataArr[44];
                    if(!dc1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(dc1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(dc1) * 10000);

                    }
                    if(!dc2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(dc2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(dc2) * 10000);

                    }
                    if(!dc3.equals("-0")) {
//                        magzDataQueue.add(Float.parseFloat(dc3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(dc3) * 10000);

                    }
                    break;
                case 5:
                    String db1 = dataArr[51].length()>10?dataArr[51].substring(0,8):dataArr[51];
                    String db2 = dataArr[52].length()>10?dataArr[52].substring(0,8):dataArr[52];
                    String db3 = dataArr[53].length()>10?dataArr[53].substring(0,8):dataArr[53];
                    if(!db1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(db1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(db1) * 10000);

                    }
                    if(!db2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(db2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(db2) * 10000);

                    }
                    if(!db3.equals("-0")) {
//                        magzDataQueue.add(Float.parseFloat(db3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(db3) * 10000);
                    }
                    break;
            }
//            if (!magxDataQueue.isEmpty()){
//                waveformViewX.addDataPoint(magxDataQueue.poll());
//            }
//            if (!magyDataQueue.isEmpty()){
//                waveformViewY.addDataPoint(magyDataQueue.poll());
//            }
//            if (!magzDataQueue.isEmpty()){
//                waveformViewZ.addDataPoint(magzDataQueue.poll());
//            }
//            startThreadx();
//            startThready();
//            startThreadz();
        }
        if(flag.equals("magbias")){
            String[] magres = processedValue.split("\n");
            System.out.println("magcor"+magres[0]+" "+magres[1]+" "+magres[2]);
            //停止画图线程
            stopThreads();
            //跳转到结果页面
            Intent intent = new Intent(MagCorActivity.this, MagResActivity.class);
            intent.putExtra("magResult",processedValue);
            startActivity(intent);

        }
    }
    /** 启动线程（只允许一个） */
    private void startThreadx() {
        if (workerThreadx != null && workerThreadx.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningx = true;
        workerThreadx = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningx) {
                    runOnUiThread(() -> {
                        if (!magxDataQueue.isEmpty()){
                            waveformViewX.addDataPoint(magxDataQueue.poll());
                        }

                    });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadx.start();
    }
    /** 启动线程（只允许一个） */
    private void startThready() {
        if (workerThready != null && workerThready.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }
        runningy = true;
        workerThready = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningy) {

                runOnUiThread(() -> {
                            if (!magyDataQueue.isEmpty()) {
                                waveformViewY.addDataPoint(magyDataQueue.poll());
                            }
                });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThready.start();
    }
    /** 启动线程（只允许一个） */
    private void startThreadz() {
        if (workerThreadz != null && workerThreadz.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningz = true;
        workerThreadz = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningz) {
                runOnUiThread(() -> {
                    if(!magzDataQueue.isEmpty()) {
                        waveformViewZ.addDataPoint(magzDataQueue.poll());
                    }
                });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadz.start();
    }

    /** 停止线程 */
    private void stopThreads() {
        runningx = false;
        runningy = false;
        runningz = false;
        if (workerThreadx != null) {
            workerThreadx.interrupt();
            workerThreadx = null;
        }
        if (workerThready != null) {
            workerThready.interrupt();
            workerThready = null;
        }
        if (workerThreadz != null) {
            workerThreadz.interrupt();
            workerThreadz = null;
        }
        //清空画图数据
        magzDataQueue.clear();
        magxDataQueue.clear();
        magyDataQueue.clear();
    }
//    private void getRawoutPlugin(String value){
//        if(saveCorrectCiliFlag==true){
//            if(saveCorrectCiliNum<correctCiliNumSum){
//                String resultRawout  = "callPlugin()";//todo
//                saveCiliArray = saveCiliArray + saveCorrectCiliNum+" "+ resultRawout+"\n";
//                saveRawArray = saveRawArray+ saveCorrectCiliNum+" "+value+"\n";
//                saveCorrectCiliNum+=1;
//            }
//            if(saveCorrectCiliNum==correctCiliNumSum){
//                String fileName = "mag-rawout-data.txt";
//                saveRawoutFile(fileName,saveCiliArray);
//                String fileName2 = "mag-rawdata.txt";
//                saveRawdataFile(fileName2,saveRawArray);
//            }
//        }
//
//    }
//    public boolean saveRawoutFile(String fileName, String content) {
//        // 检查外部存储是否可用
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("FileSave", "外部存储不可用");
//            return false;
//        }
//
//        File file = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), fileName);
//
//        try {
//            // 确保目录存在
//            File parent = file.getParentFile();
//            if (!parent.exists() && !parent.mkdirs()) {
//                Log.e("FileSave", "创建目录失败");
//                return false;
//            }
//
//            FileWriter writer = new FileWriter(file);
//            writer.write(content);
//            writer.close();
//
//            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
//            rawoutAbsFilepath=file.getAbsolutePath();
//            getMagBias();
//            return true;
//        } catch (IOException e) {
//            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
//            e.printStackTrace();
//            return false;
//        }
//    }
//    public boolean saveRawdataFile(String fileName, String content) {
//        // 检查外部存储是否可用
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("FileSave", "外部存储不可用");
//            return false;
//        }
//
//        File file = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), fileName);
//
//        try {
//            // 确保目录存在
//            File parent = file.getParentFile();
//            if (!parent.exists() && !parent.mkdirs()) {
//                Log.e("FileSave", "创建目录失败");
//                return false;
//            }
//
//            FileWriter writer = new FileWriter(file);
//            writer.write(content);
//            writer.close();
//
//            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
//            rawDataAbsFilepath=file.getAbsolutePath();
//            return true;
//        } catch (IOException e) {
//            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
//            e.printStackTrace();
//            return false;
//        }
//    }
//    private void getMagBias(){
//        //调用插件获取magBias
//        //todo
//        String resultMagbias ="callPlugin2(rawoutAbsFilepath)";
//        String filename = "magBias.txt";
//        saveMagBiasFile(filename,resultMagbias);
//    }
//    public boolean saveMagBiasFile(String fileName, String content) {
//        // 检查外部存储是否可用
//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Log.e("FileSave", "外部存储不可用");
//            return false;
//        }
//
//        File file = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOCUMENTS), fileName);
//
//        try {
//            // 确保目录存在
//            File parent = file.getParentFile();
//            if (!parent.exists() && !parent.mkdirs()) {
//                Log.e("FileSave", "创建目录失败");
//                return false;
//            }
//
//            FileWriter writer = new FileWriter(file);
//            writer.write(content);
//            writer.close();
//
//            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
//            magBiasAbsFilepath=file.getAbsolutePath();
//            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
//            SharedPreferences.Editor editor = sp.edit();
//            editor.putString("magBiasAbsFilepath", magBiasAbsFilepath);
//            editor.apply();
//            Toast.makeText(MagCorActivity.this,"校准成功",Toast.LENGTH_SHORT).show();
//            Intent magInt = new Intent(MagCorActivity.this, MagResActivity.class);
//            magInt.putExtra("deviceId",deviceId);
//            magInt.putExtra("magResult",content);
//            startActivity(magInt);
//            return true;
//        } catch (IOException e) {
//            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
//            e.printStackTrace();
//            return false;
//        }
//    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onStop() {
        super.onStop();
        stopThreads();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopThreads();
    }
}